package com.cq.smartelebicycle.fragment;

import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.cq.smartelebicycle.MainFragment;
import com.cq.smartelebicycle.R;
import com.cq.smartelebicycle.model.Music;
import com.cq.smartelebicycle.service.IMediaPlaybackService;
import com.cq.smartelebicycle.service.MediaPlaybackService;

public class MusicFragment extends Fragment implements OnClickListener, OnItemClickListener {

	public static final String TAG_ID = "MusicFragment";
	private static final int QUERY_MUSICLIST = 0;
	protected static final int UPDATE_SEEK_BAR = 1;
//	private Button musicScanner;
	private ListView musicList;
	private SeekBar musicSeek;
	private View emptyView;
	private ImageView musicPauseImg;

//	private ImageView voiceImg;
	private SeekBar voiceBar;
	private ImageView lastMusic;
	private ImageView playMusic;
	private ImageView nextMusic;

	private TextView musicTitle;
	private TextView musicTime;
	private MusicListAdapter mAdapter;
	private AsyncQueryHandler mQueryHandler = null;
	private long currentPos = -1;

	private boolean isStoped;
	private boolean pauseImgVisible = false;
	
	private AudioManager mAudioManager;

	private Handler mUiHander = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_SEEK_BAR:
				if (!isStoped) {
					updateSeekBarAndTime();
				} else {
					mUiHander.removeMessages(UPDATE_SEEK_BAR);
				}
				break;

			default:
				break;
			}

		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.music_fragment, container,
				false);
		initView(rootView);

		return rootView;
	}

	protected void updateSeekBarAndTime() {
		// TODO Auto-generated method stub
		try {
			IMediaPlaybackService mService = ((MainFragment) getActivity())
					.getMediaPlayService();
			if (mService.getCurrentPosition() < mService.getDuration()) {
				musicSeek
						.setProgress((int) ((float) mService
								.getCurrentPosition() / mService.getDuration() * musicSeek
								.getMax()));
				musicTime.setText("-"
						+ formatTime(mService.getDuration()
								- mService.getCurrentPosition()));
				mUiHander.sendEmptyMessageDelayed(UPDATE_SEEK_BAR, 1000);
			} else {
				mUiHander.removeMessages(UPDATE_SEEK_BAR);
			}

		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		mAudioManager = (AudioManager) getActivity()
				.getSystemService(Context.AUDIO_SERVICE);
		super.onCreate(savedInstanceState);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mQueryHandler = new AsyncQueryHandler(getActivity()
				.getContentResolver()) {

			@Override
			protected void onQueryComplete(int token, Object cookie,
					Cursor cursor) {
				if (token == QUERY_MUSICLIST) {
					mAdapter.changeCursor(cursor);
					mAdapter.notifyDataSetChanged();
				}
			}
		};
		mQueryHandler.startQuery(QUERY_MUSICLIST, null,
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Music.MUSIC_COLS,
				MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);

	}

	private void initView(View root) {

		musicList = (ListView) root.findViewById(R.id.music_list);
		emptyView = root.findViewById(R.id.empty);
		musicList.setEmptyView(emptyView);

		musicSeek = (SeekBar) root.findViewById(R.id.music_seek);

//		voiceImg = (ImageView) root.findViewById(R.id.ic_voice);
		voiceBar = (SeekBar) root.findViewById(R.id.voice_bar);

		nextMusic = (ImageView) root.findViewById(R.id.ic_music_next);
		lastMusic = (ImageView) root.findViewById(R.id.ic_music_last);
		playMusic = (ImageView) root.findViewById(R.id.ic_music_play);
		nextMusic.setOnClickListener(this);
		lastMusic.setOnClickListener(this);
		playMusic.setOnClickListener(this);

//		musicScanner = (Button) root.findViewById(R.id.bt_scanner);

		mAdapter = new MusicListAdapter(getActivity(), null);
		musicList.setAdapter(mAdapter);
		musicList.setOnItemClickListener(this);
		musicTitle = (TextView) root.findViewById(R.id.music_title);
		musicTime = (TextView) root.findViewById(R.id.time);

		musicSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

				IMediaPlaybackService service = ((MainFragment) getActivity())
						.getMediaPlayService();
				if (service != null) {
					try {
						service.seekTo((int) ((float) seekBar.getProgress()
								/ seekBar.getMax() * service.getDuration()));
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
			}
		});
		
		musicPauseImg = (ImageView) root.findViewById(R.id.music_pause_img);
		musicPauseImg.setOnClickListener(this);
		musicPauseImg.setVisibility(pauseImgVisible ? View.VISIBLE : View.GONE);
		voiceBar.setMax(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));  //获取最大音量值
		voiceBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)); //获取当前音量值
		voiceBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				if (fromUser) {
					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress,
							AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); //设置音量值
				}
			}
		});
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isStoped = false;
		IntentFilter mFilter = new IntentFilter(
				MediaPlaybackService.META_CHANGED);
		getActivity().registerReceiver(mMetaReceiver, mFilter);

		initOrUpdateMusicPlayUi();
		try {
			IMediaPlaybackService mService = ((MainFragment) getActivity()).getMediaPlayService();
			if (mService != null && mService.isPlaying()) {
				mUiHander.sendEmptyMessage(UPDATE_SEEK_BAR);
			}
		} catch (RemoteException e) { 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

	private void initOrUpdateMusicPlayUi() {
		// TODO Auto-generated method stub
			IMediaPlaybackService mService = ((MainFragment) getActivity())
					.getMediaPlayService();
			try {
				if (mService != null && mService.getCurrentMusicId() != MediaPlaybackService.NONE_MUSIC_ID) {
					if (mService.isPlaying()) {
						playMusic.setImageResource(R.drawable.ic_music_play);
					} else {
						playMusic.setImageResource(R.drawable.ic_music_pause);
					}
					if (currentPos != -1) {
						mAdapter.setSelectItem((int)currentPos);
						mAdapter.notifyDataSetInvalidated();
					}
					musicTitle.setText(mService.getMusicTitle());
					musicTime.setText("-" + formatTime(mService.getDuration() - mService.getCurrentPosition()));
				}
			} catch (RemoteException e) { // TODO Auto-generated catch block
				e.printStackTrace();
			}

	}
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onPause();
		isStoped = true;
		mUiHander.removeMessages(UPDATE_SEEK_BAR);
		if (mMetaReceiver != null) {
			getActivity().unregisterReceiver(mMetaReceiver);
		}
	}

	class MusicListAdapter extends CursorAdapter {

		private int selectItem;
		
		public MusicListAdapter(Context context, Cursor c) {
			super(context, c);
			// TODO Auto-generated constructor stub
		}

		public  void setSelectItem(int selectItem) {    
            this.selectItem = selectItem;    
         }    
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			// TODO Auto-generated method stub
			ViewHolder mHolder = null;
			if (view.getTag() == null) {
				mHolder = new ViewHolder();
				mHolder.index = (TextView) view.findViewById(R.id.index);
				mHolder.title = (TextView) view.findViewById(R.id.title);
				mHolder.artist = (TextView) view.findViewById(R.id.artist);
				view.setTag(mHolder);
			} else {
				mHolder = (ViewHolder) view.getTag();
			}
			Music music = new Music().initMusicFromCursor(cursor);
			mHolder.index.setText((cursor.getPosition() + 1) + ".");
			mHolder.title.setText(music.getTitle());
			mHolder.artist.setText(music.getArtist());
			
			Resources res = getActivity().getResources();
			if (selectItem == cursor.getPosition()) {
				mHolder.index.setTextColor(res.getColor(R.color.music_item_text_seleted));
				mHolder.title.setTextColor(res.getColor(R.color.music_item_text_seleted));
				mHolder.artist.setTextColor(res.getColor(R.color.music_item_text_seleted));
			} else {
				mHolder.index.setTextColor(res.getColor(R.color.music_item_text_normal));
				mHolder.title.setTextColor(res.getColor(R.color.music_item_text_normal));
				mHolder.artist.setTextColor(res.getColor(R.color.music_item_text_normal));
			}


		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			Music music = new Music().initMusicFromCursor((Cursor) super
					.getItem(position));
			return music;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(getActivity()).inflate(
					R.layout.music_list_item, null);
			return view;
		}

		class ViewHolder {
			TextView index;
			TextView title;
			TextView artist;
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mAdapter.changeCursor(null);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		IMediaPlaybackService mService = ((MainFragment) getActivity())
				.getMediaPlayService();
		if (mService != null) {
			try {
				Music music = (Music) mAdapter.getItem(position);
				boolean shouldPlay = true;
				if (mService.isPlaying()) {
					if (mService.getCurrentMusicId() == music.getId()) {
						shouldPlay = false;
						updateMusicPauseImgVisible(true);
					}
				} else {
					playMusic.setImageResource(R.drawable.ic_music_play);
				}
				if (shouldPlay) {
					musicTitle.setText(music.getTitle());
					musicTime.setText("-" + formatTime(mService.getDuration()));
					mService.setCurrentMusicId(music.getId());
					mService.play();
				} else {
					mService.pause();
					mUiHander.removeMessages(UPDATE_SEEK_BAR);
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private String formatTime(long time) {

		return DateFormat.format("mm:ss", time).toString();

	}
	

	private BroadcastReceiver mMetaReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d("luoheng", "mMetaReceiver onReceive, action=" + action);
			if (MediaPlaybackService.META_CHANGED.equals(action)) {
				currentPos = intent.getLongExtra(MediaPlaybackService.POSITION, -1);
				if (!isStoped) {
					initOrUpdateMusicPlayUi();
					mUiHander.sendEmptyMessage(UPDATE_SEEK_BAR);
				}
			}
		}
	
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		IMediaPlaybackService mService = ((MainFragment) getActivity()).getMediaPlayService();
		if (mService == null) {
			return;
		}
		try {
			switch (v.getId()) {
			case R.id.ic_music_last:
				mService.last();
				updateMusicPauseImgVisible(false);
				break;
			case R.id.ic_music_next:
				mService.next();
				updateMusicPauseImgVisible(false);
				break;
				
			case R.id.ic_music_play:
				if (mService.getCurrentMusicId() == MediaPlaybackService.NONE_MUSIC_ID) {
					if (mAdapter.getCount() > 0) {
						mService.setCurrentMusicId(((Music)mAdapter.getItem(0)).getId());
						mService.play();
						playMusic.setImageResource(R.drawable.ic_music_play);
					}
					return;
				}
				if (mService.isPlaying()) {
					updateMusicPauseImgVisible(true);
					mUiHander.removeMessages(UPDATE_SEEK_BAR);
				} else {
					updateMusicPauseImgVisible(false);
					mUiHander.sendEmptyMessage(UPDATE_SEEK_BAR);
				}
				mService.pause();
				break;
			case R.id.music_pause_img:
				updateMusicPauseImgVisible(false);
				mService.pause();
				mUiHander.sendEmptyMessage(UPDATE_SEEK_BAR);
				break;
			default:
				break;
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void updateMusicPauseImgVisible(boolean visible) {
		if (visible) {
			pauseImgVisible = true;
			musicPauseImg.setVisibility(View.VISIBLE);
			playMusic.setImageResource(R.drawable.ic_music_pause);
		} else {
			pauseImgVisible = false;
			musicPauseImg.setVisibility(View.GONE);
			playMusic.setImageResource(R.drawable.ic_music_play);
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (isStoped) {
			return false;
		}
		int vol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		switch (keyCode) {

		case KeyEvent.KEYCODE_VOLUME_DOWN:
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, --vol,
					AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); //设置音量值
			voiceBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
			return true;

		case KeyEvent.KEYCODE_VOLUME_UP:
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, ++vol,
					AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); //设置音量值
			voiceBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
			return true;
		}
		
		return false;
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (isStoped) {
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
				|| keyCode == KeyEvent.KEYCODE_VOLUME_UP) {	
			return true;
		}
		return false;
	}
	
}
